<?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends Controller {
    public function index(){
       $this->display();
    }
    public function register(){
        //接受从add.html页面提交的信息
        //注意图像的名字，需单独处理，以及PHOTOT字段的赋值
        //保存到数据库 add()
        //相关信息的验证，用户名是否存在，口令是否正确，口令加密
        $userModel = D('Users');
        //保存对象到数据库中
        if ($userModel->create()) {
            if ($_FILES['photo']['error'] == 0) {
                $fileinfo = $this->img();
                //将临时文件保存到指定位置
                $userModel->photo = $fileinfo;//获取并设置文件名称
            }
            //var_dump($userModel);
            if ($userModel->add()) {
                $this->success('注册用户成功', 'Index');
            } else {
                $this->error('注册用户失败');
            }
        } else {
            $this->error($userModel->getError());
        }

    }

    public function upload()
    {
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize = 3145728;// 设置附件上传大小
        $upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath = './Public/Uploads/photo/'; // 设置附件上传根目录
        //$upload->savePath = ''; // 设置附件上传（子）目录
        $upload->autoSub = false;
// 上传文件
        $info = $upload->upload();
        if (!$info) {
            // 上传错误提示错误信息
            $this->error($upload->getError());
        } else {// 上传成功

            return $info;
        }
    }

    public function img()
    {

        $photoinfo = $this->upload();

        $filepath = './public/Uploads/photo/';
        $oldfilename = $photoinfo['photo']['savename'];
        $oldfilefullname = $filepath . '\\' . $oldfilename;
        $newfilename = 'thumb_' . $oldfilename;
        $newfilefullname = $filepath . '\\' . $newfilename;
        $image = new \Think\Image();
        $image->open($oldfilefullname);  //注意图片的路径。
        $image->thumb(100, 100)->save($newfilefullname);
        return $newfilename;


    }
    public function login(){
        $userModel = M('Users');
        $arr['username']=I('post.username');
        $arr['pass']=I('post.pass');
        $data =$userModel->where($arr)->select();
        if($data>0){
            $this->success('登录成功','index');
        }else{
            $this->error('登录失败','index#loginmodal');
        }

    }
}